package cn.wolfcode.luowowo.job;

import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.cache.vo.StrategyStats;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class HotDataPersistenceJob{
    @Reference
    private IStrategyStatsCacheService strategyStatsCacheService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IUserInfoCacheService userInfoCacheService;
<<<<<<< HEAD

=======
>>>>>>> origin/zhiwei
    @Scheduled(cron = "0/5 * * * * ? ")
    public void persistence(){
        //System.out.println("定时刷新");
        //读取redis中的统计数据
        List<StrategyStats> list = strategyStatsCacheService.listStats();
        //遍历
        for (StrategyStats stats : list) {
            //创建
            StrategyDetail detail = new StrategyDetail();
            detail.setFavornum(stats.getFavornum());
            detail.setViewnum(stats.getViewnum());
            detail.setReplynum(stats.getReplynum());
            detail.setThumbsupnum(stats.getThumbsupnum());
            detail.setId(stats.getStrategyId());
            //调用方法更新
            strategyDetailService.updateStats(detail);
        }
<<<<<<< HEAD

=======
>>>>>>> origin/zhiwei
        //读取redis中的收藏数据
        //1.查询所有的用户
        List<UserInfo> users = userInfoService.list();
        for (UserInfo user : users) {
            Long userId = user.getId();
            //2.使用每个用户的id查询收藏攻略
            List<Long> favors = strategyStatsCacheService.getFavor(userId);
            if (favors != null && favors.size() > 0) {
                //3.获取每一个favorid并建立关系
                for (Long favorId : favors) {
                    //4.每次存入之前先查询有无已存在的收藏
                    if (strategyDetailService.isUserRelation(favorId, userId)) {
                        strategyDetailService.saveUserRelation(favorId, userId);
                    }
                }
            }
        }
        //进行访问量的落地
        //1.查询所有的用户
        List<UserInfo> userList = userInfoService.list();
        if (userList != null && userList.size() > 0) {
            for (UserInfo userInfo : userList) {
                Long userId = userInfo.getId();
                int visitorsCount = userInfoCacheService.getVisitorsRank(userId);
                userInfoService.saveVisitorsRank(visitorsCount, userId);
            }
        }
    }
}
